package com.ww.book.javaconcurrencyinpractice.ch03;

/**
 * 构造函数中启动线程导致的this引用逃逸
 */
public class ThreadStartEscape {

    private int counter = 0;

    public ThreadStartEscape() {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                increment();
            }
        });
        thread.start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 设置重要状态
        counter = 100;
    }

    public synchronized void increment() {
        counter++;
    }

    public synchronized int getCounter() {
        return counter;
    }
}
